<?php
namespace app\common;

use ErrorException;
use Exception;
use InvalidArgumentException;
use ParseError;
use PDOException;
use think\exception\ClassNotFoundException;
use think\exception\ErrorException as ExceptionErrorException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\RouteNotFoundException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
use TypeError;

/**
 * 应用异常处理类
 */
class ExceptionHandler extends Handle
{
    public function render($request, Throwable $e): Response
    {

        //如果处于调试模式
        // if (env('app_debug')) {
        //     return parent::render($request, $e);
        // }

        // 自定义异常处理
        if ($e instanceof PDOException) {
            return json($e);
        }

        // 参数验证错误
        if ($e instanceof ValidateException) {
            return json($e->getError(), 422);
        }

        if ($e instanceof ExceptionErrorException) {
            return Result::error($e->getMessage(), 400);

        }

        // 请求404异常 , 不返回错误页面
        if (($e instanceof ClassNotFoundException || $e instanceof RouteNotFoundException) || ($e instanceof HttpException && $e->getStatusCode() == 404)) {
            return Result::Error(404, '当前请求资源不存在，请稍后再试');
        }

        //请求500异常, 不返回错误页面
        if ($e instanceof Exception || $e instanceof HttpException || $e instanceof InvalidArgumentException || $e instanceof ErrorException || $e instanceof ParseError || $e instanceof TypeError) {
            return Result::Error(500, '系统异常，请稍后再试');
        }

        // 其他错误交给系统处理
        return Result::error($e->getMessage(), 500);
    }
}
